#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>

#include "QF_db_redis.h"

char *packet_full_name (const char *path, const char *name)
{
	char *full;

	if (path[0] == '/' && path[1] == '\0') {
		full = (char *)malloc (strlen (path) + strlen (name) + 1);
		full[0] = '/';
		memcpy (full + 1, name, strlen (name));
		full[strlen (name) + 1] = '\0';
		return full;
	}
	full = (char *)malloc (strlen (path) + strlen (name) + 2);
	memcpy (full, path, strlen (path));
	full[strlen (path)] = '/';
	memcpy (full + strlen (path) + 1, name, strlen (name));
	full[strlen (path) + strlen (name) + 1] = '\0';
	return full;
}

void record_info (const char *path, redis_con &db)
{
	DIR *dp = opendir (path);
	struct dirent *ent;
	char *fullname;

	if (dp == NULL) {
		perror ("Opendir");
		exit (1);
	}

	while ((ent = readdir (dp)) != NULL) {
		if (!strcmp (ent->d_name, ".") || !strcmp (ent->d_name, ".."))
			continue;
		
		fullname = packet_full_name (path, ent->d_name);

		if (ent->d_type == DT_DIR)
			record_info (fullname, db);

		if (ent->d_type == DT_REG)
			db.db_insert_one_path (fullname);

		free (fullname);
	}
}

int main (int argc, char **argv)
{
	//const char *path = "/home/herongguang/mytest/redis/QFind";
	//const char *path = "/";
	const char *path = "/home/herongguang";
	redis_con db;

	record_info (path, db);
	//db.db_debug_all_data ();
	return 0;
}
